<template>
	<view class="wrap">
		<!-- 状态栏占位 -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="dir">
				<text class="dir-text">目录</text>
				<u-icon name="arrow-down-fill" size="16" color="#666"></u-icon>
			</view>
			<view class="search-container">
				<u-search placeholder="搜索书架绘本" v-model="keyword" :show-action="false" shape="round" bg-color="#f5f5f5" height="70"></u-search>
			</view>
			<view class="search-btn">
				<u-icon name="search" size="20" color="#fff"></u-icon>
			</view>
		</view>

		<!-- Tab栏 -->
		<u-tabs :list="tabs" :is-scroll="false" :current="currentTab" @change="onTabChange"></u-tabs>

		<!-- 内容区域 -->
		<view class="content">
			<!-- 阅读计划 -->
			<view class="plan-section">
				<view class="plan-header">
					<text class="title">阅读计划</text>
					<view class="plan-actions">
						<text class="view-all" @click="goToPlanList">查看全部</text>
						<text class="create-plan" @click="goToCreatePlan">+ 创建计划</text>
					</view>
				</view>
			</view>

			<!-- 最近阅读 -->
			<view class="category-section">
				<view class="category-header">
					<text class="title">最近阅读</text>
					<u-icon name="arrow-right" color="#999"></u-icon>
				</view>
				<u-grid :col="3" :border="false">
					<u-grid-item v-for="(item, index) in recentlyRead" :key="index" @click="goToBookDetail(item)">
						<view class="book-card">
							<view class="book-cover" :style="{ background: item.color }">
								<view class="book-count">{{ item.count }}本</view>
							</view>
							<text class="book-title">{{ item.title }}</text>
							<view class="book-meta">
								<text>来自: {{ item.author }}</text>
								<u-icon name="more-dot-fill" color="#ccc"></u-icon>
							</view>
						</view>
					</u-grid-item>
				</u-grid>
			</view>

			<!-- 牛津树系列 -->
			<view class="category-section">
				<view class="category-header">
					<text class="title">牛津树系列</text>
					<u-icon name="arrow-right" color="#999"></u-icon>
				</view>
				<u-grid :col="3" :border="false">
					<u-grid-item v-for="(item, index) in oxfordTree" :key="index" @click="goToBookDetail(item)">
						<view class="book-card">
							<view class="book-cover" :style="{ background: item.color }">
								<view class="book-count">{{ item.count }}本</view>
							</view>
							<text class="book-title">{{ item.title }}</text>
							<view class="book-meta">
								<text>来自: {{ item.author }}</text>
								<u-icon name="more-dot-fill" color="#ccc"></u-icon>
							</view>
						</view>
					</u-grid-item>
				</u-grid>
			</view>
		</view>
	</view>
</template>

<script>
	import * as BookShelfApi from '@/api/bookShelf'

	export default {
		data() {
			return {
				statusBarHeight: 0,
				keyword: '',
				tabs: [{ name: '全部' }], // 默认显示全部，其他分类通过接口获取
				currentTab: 0,
				recentlyRead: [{
						count: 30,
						title: 'Jam Jam En...',
						author: '用户1026...',
						color: 'linear-gradient(to top, #c1dfc4 0%, #deecdd 100%)'
					},
					{
						count: 20,
						title: '轻松英语名...',
						author: '用户1026...',
						color: 'linear-gradient(to top, #f0c987 0%, #f9e4c3 100%)'
					},
					{
						count: 28,
						title: 'Henry and M...',
						author: '用户1026...',
						color: 'linear-gradient(to top, #f29a9a 0%, #f7d8d8 100%)'
					}
				],
				oxfordTree: [] // 动态从接口获取数据
			};
		},
		async onLoad() {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight || 0;
			
			// 检查登录状态
			if (this.checkLoginStatus()) {
				// 获取中文书架分类数据
				await this.loadCategoryData();
				// 获取绘本数据
				await this.loadBookData();
			}
		},
		methods: {
			// 检查登录状态
			checkLoginStatus() {
				const token = this.$store.getters.token;
				if (!token) {
					// 没有token，跳转到登录页面
					uni.showModal({
						title: '提示',
						content: '请先登录后再使用此功能',
						confirmText: '去登录',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/login/index'
								});
							}
						}
					});
					return false;
				}
				return true;
			},
			// 加载分类数据
			async loadCategoryData() {
				try {
					// 调用接口获取中文书架分类数据，type=2表示中文书架
					const response = await BookShelfApi.getCategoryListByType('2');
					if (response.code === 200 && response.data) {
						// 将接口返回的分类数据转换为tabs格式
						const categoryTabs = response.data.map(item => ({
							name: item.catalogueName || item.categoryName,
							id: item.id
						}));
						// 保留"全部"选项，并添加从接口获取的分类
						this.tabs = [{ name: '全部' }, ...categoryTabs];
					} else if (response.code === 0 && response.data) {
						// 处理 code 为 0 的情况
						const categoryTabs = response.data.map(item => ({
							name: item.catalogueName || item.categoryName,
							id: item.id
						}));
						this.tabs = [{ name: '全部' }, ...categoryTabs];
					}
				} catch (error) {
					console.error('获取分类数据失败:', error);
					// 检查是否是认证错误
					if (error.result && error.result.code === 401) {
						// 401错误已经在 request 拦截器中处理，这里不需要额外处理
						return;
					}
					// 如果接口调用失败，使用默认的分类数据
					this.tabs = [{ name: '全部' }, { name: '分级阅读' }, { name: '桥梁书' }, { name: '章节书' }, { name: '其它' }];
				}
			},
			async onTabChange(index) {
				this.currentTab = index;
				console.log('当前选中的tab索引:', index);
				
				// 根据选中的分类重新加载绘本数据
				if (index === 0) {
					// 选择"全部"时，加载所有绘本
					await this.loadBookData();
				} else {
					// 选择特定分类时，根据分类名称过滤绘本
					const selectedCategory = this.tabs[index];
					if (selectedCategory && selectedCategory.name) {
						await this.loadBookDataByCategory(selectedCategory.name);
					}
				}
			},
			goToCreatePlan() {
				uni.navigateTo({
					url: '/pages/plan/create'
				});
			},
			goToPlanList() {
				uni.navigateTo({
					url: '/pages/plan/index'
				});
			},
			goToBookDetail(item) {
				// 构建详情页面参数
				const params = {
					title: item.title,
					id: item.id || '',
					catalogueId: item.catalogueId || '',
					categoryName: item.categoryName || '',
					author: item.author || ''
				};
				
				// 将参数转换为URL查询字符串
				const queryString = Object.keys(params)
					.filter(key => params[key] !== '')
					.map(key => `${key}=${encodeURIComponent(params[key])}`)
					.join('&');
				
				uni.navigateTo({
					url: `/pages/book/bookDetail?${queryString}`
				});
			},
			// 加载绘本数据
			async loadBookData() {
				try {
					// 调用接口获取中文书架绘本数据
					const response = await BookShelfApi.getCategoryList({
						type: '2', // 中文书架
						recycleBin: 'false' // 不包含回收站
					});
					
					if ((response.code === 200 || response.code === 0) && response.data) {
						// 生成渐变色数组
						const gradients = [
							'linear-gradient(to top, #d4e3a9 0%, #e9f1d2 100%)',
							'linear-gradient(to top, #a7d8de 0%, #d8eef1 100%)',
							'linear-gradient(to top, #e3c4e3 0%, #f1e2f1 100%)',
							'linear-gradient(to top, #f0c987 0%, #f9e4c3 100%)',
							'linear-gradient(to top, #f29a9a 0%, #f7d8d8 100%)',
							'linear-gradient(to top, #c1dfc4 0%, #deecdd 100%)'
						];
						
						// 处理绘本数据
						const bookData = [];
						response.data.forEach((category, categoryIndex) => {
							if (category.bookShelfSaveRespVOList && category.bookShelfSaveRespVOList.length > 0) {
								category.bookShelfSaveRespVOList.forEach((book, bookIndex) => {
									bookData.push({
										id: book.id,
										title: book.title,
										count: book.quantity || 0,
										author: book.createName || '未知作者',
										color: gradients[(categoryIndex + bookIndex) % gradients.length],
										catalogueId: book.catalogueId,
										categoryName: category.categoryName
									});
								});
							}
						});
						
						// 更新牛津树数据，取前6个绘本
						this.oxfordTree = bookData.slice(0, 6);
					} else {
						console.warn('获取绘本数据失败，使用默认数据');
						// 使用默认数据
						this.oxfordTree = [
							{
								count: 59,
								title: '中文绘本1',
								author: '用户10...',
								color: 'linear-gradient(to top, #d4e3a9 0%, #e9f1d2 100%)'
							},
							{
								count: 47,
								title: '中文绘本2',
								author: '用户10...',
								color: 'linear-gradient(to top, #a7d8de 0%, #d8eef1 100%)'
							},
							{
								count: 42,
								title: '中文绘本3',
								author: '用户10...',
								color: 'linear-gradient(to top, #e3c4e3 0%, #f1e2f1 100%)'
							}
						];
					}
				} catch (error) {
					console.error('获取绘本数据失败:', error);
					// 使用默认数据
					this.oxfordTree = [
						{
							count: 59,
							title: '中文绘本1',
							author: '用户10...',
							color: 'linear-gradient(to top, #d4e3a9 0%, #e9f1d2 100%)'
						},
						{
							count: 47,
							title: '中文绘本2',
							author: '用户10...',
							color: 'linear-gradient(to top, #a7d8de 0%, #d8eef1 100%)'
						},
						{
							count: 42,
							title: '中文绘本3',
							author: '用户10...',
							color: 'linear-gradient(to top, #e3c4e3 0%, #f1e2f1 100%)'
						}
					];
				}
			},
			// 根据分类名称加载绘本数据
			async loadBookDataByCategory(categoryName) {
				try {
					// 调用接口获取特定分类的中文书架绘本数据
					const response = await BookShelfApi.getCategoryList({
						type: '2', // 中文书架
						recycleBin: 'false', // 不包含回收站
						categoryName: categoryName // 指定分类名称
					});
					
					if ((response.code === 200 || response.code === 0) && response.data) {
						// 生成渐变色数组
						const gradients = [
							'linear-gradient(to top, #d4e3a9 0%, #e9f1d2 100%)',
							'linear-gradient(to top, #a7d8de 0%, #d8eef1 100%)',
							'linear-gradient(to top, #e3c4e3 0%, #f1e2f1 100%)',
							'linear-gradient(to top, #f0c987 0%, #f9e4c3 100%)',
							'linear-gradient(to top, #f29a9a 0%, #f7d8d8 100%)',
							'linear-gradient(to top, #c1dfc4 0%, #deecdd 100%)'
						];
						
						// 处理绘本数据
						const bookData = [];
						response.data.forEach((category, categoryIndex) => {
							if (category.bookShelfSaveRespVOList && category.bookShelfSaveRespVOList.length > 0) {
								category.bookShelfSaveRespVOList.forEach((book, bookIndex) => {
									bookData.push({
										id: book.id,
										title: book.title,
										count: book.quantity || 0,
										author: book.createName || '未知作者',
										color: gradients[(categoryIndex + bookIndex) % gradients.length],
										catalogueId: book.catalogueId,
										categoryName: category.categoryName
									});
								});
							}
						});
						
						// 更新牛津树数据
						this.oxfordTree = bookData.slice(0, 6);
					} else {
						console.warn(`获取分类"${categoryName}"的绘本数据失败`);
						// 如果没有数据，清空显示
						this.oxfordTree = [];
					}
				} catch (error) {
					console.error(`获取分类"${categoryName}"的绘本数据失败:`, error);
					// 如果接口调用失败，清空显示
					this.oxfordTree = [];
				}
			}
		}
	};
</script>

<style lang="scss">
	.wrap {
		padding: 10rpx;
		background-color: #fff;
	}

	.status-bar {
		width: 100%;
		background-color: #fff;
	}

	.search-bar {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		gap: 20rpx;
	}

	.dir {
		display: flex;
		align-items: center;
		gap: 8rpx;
		flex-shrink: 0;
	}

	.dir-text {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	.search-container {
		flex: 1;
		margin: 0 20rpx;
	}

	.search-btn {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
		background-color: #ff8c00;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
		box-shadow: 0 4rpx 12rpx rgba(255, 140, 0, 0.3);
	}

	.content {
		padding: 20rpx;
	}

	.plan-section {
		padding: 20rpx 0;
	}

	.plan-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.title {
		font-size: 32rpx;
		font-weight: bold;
		color: #007aff;
	}

	.plan-actions {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.view-all {
		color: #666;
		font-size: 26rpx;
	}

	.create-plan {
		color: #000;
		font-size: 28rpx;
	}

	.category-section {
		margin-top: 30rpx;
	}

	.category-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.book-card {
		width: 95%;
		display: flex;
		flex-direction: column;
		margin-bottom: 20rpx;
	}

	.book-cover {
		height: 150rpx;
		border-radius: 12rpx;
		position: relative;
		margin-bottom: 10rpx;
	}

	.book-count {
		position: absolute;
		top: 10rpx;
		left: 10rpx;
		background-color: rgba(0, 0, 0, 0.3);
		color: white;
		padding: 2rpx 10rpx;
		border-radius: 20rpx;
		font-size: 20rpx;
	}

	.book-title {
		font-size: 26rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.book-meta {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 22rpx;
		color: #999;
	}
</style>